﻿using System;
using System.Data.Entity.Migrations.Model;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using mshtml;

namespace YogaDictionary.ViewModel
{
    public class WebBrowserHelper
    {
        public static readonly DependencyProperty BodyProperty =
            DependencyProperty.RegisterAttached("Body", typeof(string), typeof(WebBrowserHelper), new PropertyMetadata(OnBodyChanged));

        public static string GetBody(DependencyObject dependencyObject)
        {
            return (string)dependencyObject.GetValue(BodyProperty);
        }

        public static void SetBody(DependencyObject dependencyObject, string body)
        {
            dependencyObject.SetValue(BodyProperty, body);
        }

        private static void OnBodyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            var msg = "<head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></head><body scroll=no>";
            msg += (string) e.NewValue;
            msg += "</body>";
            var webBrowser = (WebBrowser)d;
            webBrowser.NavigateToString(msg);
            webBrowser.LoadCompleted -= WebBrowserOnLoadCompleted;
            webBrowser.LoadCompleted += WebBrowserOnLoadCompleted;
        }

        private static void WebBrowserOnLoadCompleted(object d, NavigationEventArgs navigationEventArgs)
        {
            UpdateWebBrowserHeight((WebBrowser)d);
        }

        private static void UpdateWebBrowserHeight(WebBrowser webBrowser)
        {
            var doc = (IHTMLDocument2)webBrowser.Document;
            var height = ((IHTMLElement2)doc.body).scrollHeight;
            webBrowser.Height = Math.Min(height, (int)SystemParameters.WorkArea.Height - 100);
        }

    }
}
